package com.acme.team3.chat;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

import com.acme.team03.net.client.ClientMessageHandler;
import com.acme.team03.net.server.ConnectionDispatcher;

public class Main {

	static ExecutorService singleThread = Executors.newSingleThreadExecutor();
	

	private static Hashtable<String, CommandHandler> getHandlers() {
		Hashtable<String, CommandHandler> handlers = new Hashtable<>();
		handlers.put("snd", new SendCommandHandler(connDisp));
		handlers.put("hist", new HistoryCommandHandler(connDisp));
		handlers.put("exit", new CommandHandler() {
			@Override
			public void handle(Command cmd) {
				stopIt.set(true);
			}
		});
		handlers.put(Command.INCORRECT_COMMAND, new CommandHandler() {
			@Override
			public void handle(Command cmd) {
				System.out.println("Incorrect command. Sorry...");
				;
			}
		});
		return handlers;
	}

	private static AtomicBoolean stopIt = new AtomicBoolean(false);
	private static ConnectionDispatcher connDisp;
	private static ClientMessageHandler clientMessageHandler;

	/**
	 * @param args
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public static void main(String[] args) throws UnknownHostException,
			IOException {
		connDisp = new ConnectionDispatcher();
		clientMessageHandler = new ClientMessageHandler(connDisp);
		if (args.length < 1) {
			connDisp.establishConnection(new Socket("127.0.0.1", 7777),
					clientMessageHandler);
		} else {
			connDisp.establishConnection(new Socket(args[0], 7777),
					clientMessageHandler);
		}
		singleThread.execute(clientMessageHandler);
		Hashtable<String, CommandHandler> handlers = getHandlers();
		Scanner sc = new Scanner(System.in);
		while (!stopIt.get()) {
			String str = sc.nextLine();
			Command cmd = new Command(str);
			handlers.get(cmd.getCmd()).handle(cmd);
		}
		connDisp.closeAllConnections();
		singleThread.shutdownNow();
		sc.close();
	}

}